package com.hyts.distlock.handler;

import com.hyts.distlock.config.LockConfig;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

/**
 * project-name:coffice-toolbox
 * package-name:com.hyts.distlock.handler
 * author:Libo/Alex
 * create-date:2019-05-11 09:47
 * copyright:libo-hyts-github
 * email:libo2dev@aliyun.com
 * description:此类主要用于: zookeeper原生的数据客户端对象
 */
public class ZkOriginHandler implements Watcher {

    /**
     * 日志
     */
    Logger logger = LoggerFactory.getLogger(ZkOriginHandler.class);

    String rootLockPath;

    /**
     * @param host
     * @param port
     * @param timeout
     * @param rootLockPath
     * @return
     */
    public ZooKeeper build(String host,int port,int timeout,String rootLockPath){
        ZooKeeper zookeeper = null;
        try {
            zookeeper = new ZooKeeper(host+":"+port,(timeout*1000),this);
            if(rootLockPath == null || "".equals(rootLockPath)){
                this.rootLockPath = LockConfig.LOCK_ZOOKEEPER_PREFIX;
                Stat stat = zookeeper.exists(this.rootLockPath,false);
                if(stat == null){
                    zookeeper.create(this.rootLockPath, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
                }
            }
            zookeeper.create(LockConfig.LOCK_METADATA,rootLockPath.getBytes(Charset.forName("UTF-8")),ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        } catch (IOException | KeeperException | InterruptedException e) {
            logger.error("构建Zookeeper对象失败!",e);
        }
        return zookeeper;
    }

    /**
     * @param host
     * @param port
     * @param timeout
     * @return
     */
    public ZooKeeper build(String host,int port,int timeout){
       return build(host,port,timeout,null);
    }

    /**
     * @param host
     * @param port
     * @return
     */
    public ZooKeeper build(String host,int port){
        return build(host,port,LockConfig.ZOOKEEPER_CONNECTION_TIMEOUT);
    }


    /**
     * @param host
     * @return
     */
    public ZooKeeper build(String host){
        return build(host,6379,LockConfig.ZOOKEEPER_CONNECTION_TIMEOUT);
    }

    /**
     * @param port
     * @return
     */
    public ZooKeeper build(int port){
        return build("127.0.0.1",port,LockConfig.ZOOKEEPER_CONNECTION_TIMEOUT);
    }

    /**
     * @return
     */
    public ZooKeeper build(){
        return build("127.0.0.1",6379,LockConfig.ZOOKEEPER_CONNECTION_TIMEOUT);
    }


    @Override
    public void process(WatchedEvent watchedEvent) {

    }


}
